{
 "cells": [
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "我们使用Sequential容器构建模型结构"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "\n",
    "# 定义一个包含两个nn.Conv2d层的序列模型\n",
    "model = nn.Sequential(\n",
    "    nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1),\n",
    "    nn.ReLU(),  # 通常卷积层后会接一个激活函数\n",
    "    nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1),\n",
    "    nn.ReLU()  # 第二个卷积层后也接一个激活函数\n",
    ")\n",
    "\n",
    "# 定义一个输入张量，大小为(1, 3, 28, 28)，表示batch_size为1，通道数为3，图像尺寸为28x28\n",
    "input_tensor = torch.randn(1, 3, 28, 28)\n",
    "\n",
    "# 将输入张量传递给模型进行前向计算\n",
    "output_tensor = model(input_tensor)\n",
    "\n",
    "# 输出张量的形状，具体取决于卷积层的参数和输入尺寸\n",
    "print(output_tensor.shape)"
   ]
  },
  {
   "cell_type": "markdown",
   "metadata": {},
   "source": [
    "使用经典的Class风格组织模型结构"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "metadata": {},
   "outputs": [],
   "source": [
    "import torch\n",
    "import torch.nn as nn\n",
    "\n",
    "class MyConvNet(nn.Module):\n",
    "    def __init__(self):\n",
    "        super(MyConvNet, self).__init__()\n",
    "        # 定义第一个卷积层\n",
    "        self.conv1 = nn.Conv2d(in_channels=3, out_channels=16, kernel_size=3, stride=1, padding=1)\n",
    "        # 定义第二个卷积层\n",
    "        self.conv2 = nn.Conv2d(in_channels=16, out_channels=32, kernel_size=3, stride=1, padding=1)\n",
    "        # 也可以在这里定义其他层，比如激活函数、池化层等\n",
    "\n",
    "    def forward(self, x):\n",
    "        # 前向传播，将输入x传递给第一个卷积层，然后传递给ReLU激活函数\n",
    "        x = nn.functional.relu(self.conv1(x))\n",
    "        # 将激活后的输出传递给第二个卷积层，然后再次传递给ReLU激活函数\n",
    "        x = nn.functional.relu(self.conv2(x))\n",
    "        # 返回最终的输出\n",
    "        return x\n",
    "\n",
    "# 实例化自定义网络模型\n",
    "model = MyConvNet()\n",
    "\n",
    "# 定义一个输入张量，大小为(1, 3, 28, 28)，表示batch_size为1，通道数为3，图像尺寸为28x28\n",
    "input_tensor = torch.randn(1, 3, 28, 28)\n",
    "\n",
    "# 将输入张量传递给模型进行前向计算\n",
    "output_tensor = model(input_tensor)\n",
    "\n",
    "# 输出张量的形状，具体取决于卷积层的参数和输入尺寸\n",
    "print(output_tensor.shape)"
   ]
  }
 ],
 "metadata": {
  "language_info": {
   "name": "python"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
